import React, { useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import { Swiper, Toast, Badge, Popup } from 'react-vant';
import styles from './detail.module.scss'
import { Button, Card, NavBar, } from 'antd-mobile'
import { CartO, ServiceO, } from '@react-vant/icons'
import { ActionBar } from 'react-vant'
import parse from 'html-react-parser'
import { useAppDispatch, useAppSelector } from '../../store/store'       // 全局 dispatch/selector
import { addToCart, selectCartCount } from '../../store/cartSlice'        // 加入购物车 action与数量选择器
import { useNavigate } from 'react-router-dom'      
import { getDetailList, getDetailList1, getDetailList2 } from '../../api/detailService'
const Index = () => {
  const nav = useNavigate()
  const dispatch = useAppDispatch()  // 放在函数组件开头
  const { shop_spu_id } = useParams()
  const [List, setList] = useState<any>({}) // getDetailList 返回的规格/sku 数据对象
  const [listinfo, setListinfo] = useState<any>({})
  const [listtail, setListtail] = useState<any>({})
  // 底部弹框所需状态
  const [buyVisible, setBuyVisible] = useState(false) // 弹框显隐
  const [buyQty, setBuyQty] = useState(1) // 购买数量
  const [popupMode, setPopupMode] = useState<'add'|'buy'>('add') // 模式：加入/购买
  const [selectedSpec, setSelectedSpec] = useState<string>('') // 已选规格
  // 规格文案数组：从 List.specification_info[0].options 提取 value/name/text/字符串
  const specTexts = useMemo<string[]>(() => {
  const info = (List as any)?.specification_info;
  // 可能是数组，也可能是对象里就有 options
  const options =
    Array.isArray(info)
      ? info?.[0]?.options
      : (info?.options || info?.[0]?.options);

  if (!Array.isArray(options)) return [];
  return options.map((opt: any, i: number) =>
    typeof opt === 'string'
      ? opt
      : (opt?.value || opt?.name || opt?.text || String(i))
  );
}, [List]);

useEffect(() => {
  if (specTexts.length > 0) {
    setSelectedSpec((prev) => prev || specTexts[0]);
  }
  
}, [specTexts]);
  // 初始化“已选规格”
  useEffect(() => {
    if (!selectedSpec && specTexts.length > 0) setSelectedSpec(specTexts[0])
      console.log('List:', List);
console.log('spec_info:', List?.specification_info);
console.log('options:', Array.isArray(List?.specification_info) ? List.specification_info[0]?.options : List?.specification_info?.options);
  }, [specTexts, selectedSpec])
 
  const cartCount = useAppSelector(selectCartCount) // 购物车数量徽标
  const getList = async (shopSpuId: string) => {
    try {
       const res = await getDetailList(shopSpuId) // 已返回数据本体（不是 res.data）
       console.log('getDetailList:', res)
       setList(res || {}) // 保存规格/sku 数据到 List（对象）
      const base = await getDetailList1(shopSpuId)
      console.log('2', base.data);
      setListinfo(base.data)
      console.log(listinfo, '22');

      const tail = await getDetailList2(shopSpuId)
      console.log('3', tail.data);
      setListtail(tail.data || [])
    } catch (err) {
      console.error('获取商品详情失败:', err)
    }
  }
  useEffect(() => {
    if (shop_spu_id) {
      getList(shop_spu_id as string)
    }
  }, [shop_spu_id])

  // 监听 listinfo 状态变化，用于调试
  useEffect(() => {
    console.log('listinfo 状态已更新:', listinfo);
    if (listinfo?.express_info?.service_info_list) {
      console.log('service_info_list 数据:', listinfo.express_info.service_info_list);
    }
  }, [listinfo])
  // 监听 List（getDetailList 返回）用于调试
  useEffect(() => {
    console.log('List 状态已更新:', List)
  }, [List])
  return (
    <div className={styles.detailbox}>
      <NavBar onBack={() => nav(-1)}>详情</NavBar>
      {/* 轮播图 */}
      <div className="demo-swiper" style={{ position: 'relative' }}>
        {listinfo?.swiper_info?.img_list && listinfo.swiper_info.img_list.length > 0 ? (
          <Swiper
            indicator={(total, current) => (
              <div style={{
                position: 'absolute',
                bottom: '12px',
                right: '12px',
                background: 'rgba(0, 0, 0, 0.5)',
                color: 'white',
                padding: '4px 8px',
                borderRadius: '12px',
                fontSize: '12px',
                zIndex: 10
              }}>
                {current + 1}/{total}
              </div>
            )}
          >
            {listinfo.swiper_info.img_list.map((img: string, index: number) => (
              <Swiper.Item key={index}>
                <img
                  src={img}
                  alt={`商品图片 ${index + 1}`}
                  style={{ width: '100%', height: '300px', objectFit: 'cover' }}
                />
              </Swiper.Item>
            ))}
          </Swiper>
        ) : (
          <div style={{ padding: '20px', textAlign: 'center' }}>
            图片加载中...
          </div>
        )}
      </div>
      {/* 商品基本信息 */}
      {listinfo?.goods_info && (
        <Card className={styles.card}>
          <div className={styles.shopbox}>
            <p className={styles.picbox}>
              <span>¥</span> {listinfo.goods_info.price}
            </p>
            <p className={styles.titlep}>
              {String(listinfo?.goods_info?.tag || listinfo?.goods_info?.tags || '')
                .toUpperCase()
                .includes('OTC') && (
                <span
                  style={{
                    display: 'inline-block',
                    background: '#00C853',
                    color: '#fff',
                    borderRadius: '6px',
                    padding: '2px 6px',
                    fontSize: '14px',
                    marginRight: '6px',
                    verticalAlign: 'middle',
                    marginTop:'-5px'
                  }}
                >
                  OTC
                </span>
              )}
              {listinfo.goods_info.title}
            </p>
          </div>
        </Card>

      )}

      {/* 服务信息 */}
      {listinfo?.express_info && (
        <div className={styles.fwbox} >
          <p className={styles.fwboxitem}>
            <span className={styles.sp}>发货</span>  {listinfo.express_info.shop_name}
          </p>
          <p className={styles.fwboxitem}>
            <span className={styles.sp}> 运费 </span>{listinfo.express_info.express_tip}
          </p>
          <div>
            {listinfo.express_info.service_info_list && listinfo.express_info.service_info_list.length > 0 && (
              <div className={styles.fwboxbom} style={{ display: 'flex', }}>
                <span className={styles.sp}>服务</span>
                {listinfo.express_info.service_info_list.map((service: any, index: number) => (
                  <div
                    key={index}
                  >
                    <div>
                      <img
                        src={service.icon}
                        alt={service.title}
                        style={{ width: '13px', height: '13px', paddingTop:'2px',marginRight:'2px'}}
                      /> <span className={styles.imgspan} >{service.title}</span>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>



        </div>
      )}
      <div className={styles.shopdetabox}>
        <p>商品详情</p>
      </div>
      <div className={styles.pichop}>
        <p className={styles.sfts}>消费提示</p>
        <div>
          {listtail?.detail_page ? parse(listtail.detail_page) : '暂无内容'}
          <img src={listtail?.warm_price_img_url} alt="" />
        </div>
      </div>
      <div className={styles.bombox}>
      </div>
      <div className='demo-action-bar'>
        <ActionBar>
          {/* 客服 */}
          <ActionBar.Icon icon={<ServiceO />} text='客服' />
          {/* 购物车 + 数量徽标 */}
          <ActionBar.Icon
            icon={<Badge content={cartCount > 0 ? cartCount : null}><CartO /></Badge>}
            text='购物车'
            onClick={() => nav('/shoppcat')}
          />
          {/* 加入购物车：弹出底部弹框 */}
          <ActionBar.Button
            type='warning'
            text='加入购物车'
            onClick={() => {
              setPopupMode('add')
              setBuyQty(1)
              setBuyVisible(true)
            }}
          />
          {/* 立即购买：弹出底部弹框 */}
          <ActionBar.Button
            type='danger'
            text='立即购买'
            onClick={() => {
              setPopupMode('buy')
              setBuyQty(1)
              setBuyVisible(true)
            }}
          />
        </ActionBar>
      </div>
      {/* 底部弹框：用 List 渲染，与截图一致 */}
      <Popup visible={buyVisible} round position='bottom' onClose={() => setBuyVisible(false)}>
        <div style={{ padding: 16 }}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <img
              src={
                (Array.isArray((List as any)?.specification_sku_info)
                  ? (List as any)?.specification_sku_info?.[0]?.img
                  : (List as any)?.specification_sku_info?.img) || listinfo?.swiper_info?.img_list?.[0]
              }
              style={{ width: 72, height: 72, borderRadius: 6, objectFit: 'cover' }}
            />
            <div style={{ flex: 1 }}>
              <div style={{ color: '#ff4d4f', fontSize: 20, fontWeight: 600 }}>
                ¥{Number((List as any)?.specification_sku_info?.price ?? (List as any)?.price ?? listinfo?.goods_info?.price ?? 0)}
              </div>
              <div style={{ color: '#999', marginTop: 6 }}>剩余 {Number((List as any)?.specification_sku_info?.stock ?? listinfo?.goods_info?.stock ?? 0)} 件</div>
              <div style={{ color: '#999', marginTop: 6 }}>已选 {selectedSpec || '默认规格'}</div>
            </div>
          </div>
          {/* 规格 */}
          {specTexts.length > 0 && (
            <div style={{ marginTop: 16 }}>
              <div style={{ color: '#333', marginBottom: 10 }}>规格</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
                {specTexts.map(text => {
                  const selected = selectedSpec === text
                  return (
                    <div
                      key={text}
                      onClick={() => setSelectedSpec(text)}
                      style={{
                        padding: '10px 14px',
                        borderRadius: 8,
                        border: selected ? '1px solid rgba(255,77,79,.35)' : '1px solid #f4d8d8',
                        background: selected ? 'rgba(255,77,79,.12)' : '#fff5f5',
                        color: '#ff4d4f', cursor: 'pointer'
                      }}
                    >{text}</div>
                  )
                })}
              </div>
            </div>
          )}
          {/* 数量 */}
          <div style={{ marginTop: 16 }}>
            <div style={{ color: '#333', marginBottom: 10 }}>购买数量</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <button onClick={() => setBuyQty(q => Math.max(1, q - 1))} style={{ width: 36, height: 32, borderRadius: 6, border: '1px solid #eee' }}>–</button>
              <div style={{ width: 32, textAlign: 'center' }}>{buyQty}</div>
              <button onClick={() => setBuyQty(q => q + 1)} style={{ width: 36, height: 32, borderRadius: 6, border: '1px solid #eee' }}>+</button>
            </div>
          </div>
          {/* 确定 */}
          <div style={{ marginTop: 24 }}>
            <button
              onClick={() => {
                dispatch(addToCart({
                  shopSpuId: String(shop_spu_id || listinfo?.shop_spu_id || ''),
                  skuId: undefined,
                  title: listinfo?.goods_info?.title || '',
                  image: (Array.isArray((List as any)?.specification_sku_info)
                    ? (List as any)?.specification_sku_info?.[0]?.img
                    : (List as any)?.specification_sku_info?.img) || listinfo?.swiper_info?.img_list?.[0],
                  price: Number((List as any)?.specification_sku_info?.price ?? (List as any)?.price ?? listinfo?.goods_info?.price ?? 0),
                  quantity: buyQty,
                  tag: listinfo?.goods_info?.tag,
                  selectedSpecsText: selectedSpec || undefined
                } as any) as any)
                setBuyVisible(false)
                if (popupMode === 'buy') nav('/shoppcat')
                else Toast.success('已加入购物车')
              }}
              style={{ width: '100%', height: 44, borderRadius: 22, border: 'none', color: '#fff', background: 'linear-gradient(90deg,#FF9F41,#FF3B30)' }}
            >确定</button>
          </div>
        </div>
      </Popup>
      {/* 已移除所有底部弹框代码 */}

    </div>
  )
}

export default Index
